﻿using System;
using System.IO;

namespace TestApp
{

    public class DefaultFormatProvider : IFormatProvider
    {
        public static DefaultFormatProvider Provider { get; private set; }

        static DefaultFormatProvider() { Provider = new DefaultFormatProvider(); }

        private DefaultFormatProvider() { }

        public object GetFormat(Type formatType)
        {
            return null;
        }
    }

    internal sealed class StringStorage : BaseStorage
    {
        public override T ReadFromKey<T>(string key)
        {
            try
            {
                Type type = typeof(T);

                using (var fs = storage.OpenFile(key, FileMode.OpenOrCreate))
                using (StreamReader sr = new StreamReader(fs))
                {
                    string value = sr.ReadToEnd();
                    if (string.IsNullOrEmpty(value))
                    {
                        return default(T);
                    }

                    return (T)System.Convert.ChangeType(value, type, DefaultFormatProvider.Provider);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                throw;
            }
        }

        public override void WriteWithKey(object obj, string key)
        {
            try
            {
                if (obj == null)
                {
                    return;
                }

                using (var fs = storage.CreateFile(key))
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.Write(obj);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                throw;
            }
        }

        protected override string Extension
        {
            get { return "string"; }
        }
    }
}
